class ApplicationError < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user_id
  validates_presence_of :subject, :content, :unless => :is_multirequest?
  attr_accessor :user_crypted_key, :multirequest

  def initialize(attributes)
    super(attributes)
    if user_crypted_key
      self.user = User.find_by_crypted_key(user_crypted_key) 
    end
  end
  def is_multirequest
    return multirequest == 'yes'
  end
  def user_agent=(agent)
    write_attribute(:user_agent, agent)
    
    if agent.include?"Firefox"
      self.browser = "Firefox"
    elsif agent.include? "MSIE"
      self.browser = "Internet Explorer"
    elsif agent.include? "AppleWebKit"
      self.browser = "WebKit"
    elsif agent.include? "Opera"
      self.browser = "Opera"
    else
      self.browser = "Unknown"
    end
  end
  def content=(c)
    write_attribute(:content, c)
    res = c.match(/HTML Content:\n     (.*)/m)
    if(res)
      self.compare = res.pre_match
    end
  end
  
  def subject_preview(length = 75)
    subject[0...length]+(subject.length > length ? ' ...' : '' )
  end
  
  def content_preview(length = 100)
    content[0...length]+(content.length > length ? ' ...' : '' )
  end
  
  def self.most_common(user)
    ApplicationError.find(:all,  :order => 'count DESC',
                                :limit => 5,
                                :select => "compare, subject, count(*) as count",
                                :group =>  "compare",
                                :conditions => 'compare is not null AND status != "closed" AND user_id = '+user.id.to_s)
  end
  
end
